package com.soar.recruitment.common.ui.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.soar.recruitment.R;
import com.soar.recruitment.common.bll.SOARHttpCallback;
import com.soar.recruitment.common.dal.model.SOARBaseModel;
import com.soar.recruitment.common.ui.view.roundview.RoundTextView;
import com.soar.recruitment.common.util.MyToast;
import com.soar.recruitment.common.util.SoarLoadDialog;
import com.soar.recruitment.common.util.ValidityUtils;
import com.soar.recruitment.module.user.bll.api.UserApi;
import com.soar.recruitment.module.user.dal.bean.UserModel;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import okhttp3.Request;

public class MyEditView extends FrameLayout {

    public static final int TYPE_DEFAULT = 0;
    public static final int TYPE_PHONE = 1;
    public static final int TYPE_PASSWORD = 2;
    public static final int TYPE_AUTHCODE = 3;
    private static final int AUTHCODE_INTERVAL = 60 * 1000;

    private UserApi mUserApi;

    ImageView leftImage;
    EditText editText;
    ImageView clearBtn;
    ImageView eyeBtn;
    RoundTextView getAuthcodeTV;
    View bottomLine;
    MyCountDownTimer myCountDownTimer;
    private String authPhone;
    private String authType;
    private String authImage;

    // 默认是注册的获取验证码
    private boolean mIsRegister = true;

    private int type = TYPE_DEFAULT;
    private int mInputCount;

    public MyEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyEditView);
        type = typedArray.getInteger(R.styleable.MyEditView_type, TYPE_PHONE);
        typedArray.recycle();
        initView();
    }

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_edit_text, this);
        leftImage = ButterKnife.findById(this, R.id.leftImage);
        editText = ButterKnife.findById(this, R.id.editText);
        clearBtn = ButterKnife.findById(this, R.id.clearBtn);
        eyeBtn = ButterKnife.findById(this, R.id.eyeBtn);
        getAuthcodeTV = ButterKnife.findById(this, R.id.getAuthcodeTV);
        bottomLine = ButterKnife.findById(this, R.id.bottomLine);

        switch (type) {
            case TYPE_DEFAULT:
                break;
            case TYPE_PHONE:
                leftImage.setImageResource(R.drawable.login_phone_selector);
                editText.setInputType(InputType.TYPE_CLASS_PHONE);
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                break;
            case TYPE_PASSWORD:
                editText.setHint("请输入密码");
                leftImage.setImageResource(R.drawable.login_password_selector);
                editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                break;
            case TYPE_AUTHCODE:
                editText.setHint("请输入短信验证码");
                leftImage.setImageResource(R.drawable.login_authcode_selector);
                getAuthcodeTV.setVisibility(VISIBLE);
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                break;
        }

        editText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                bottomLine.setSelected(hasFocus);
                if (hasFocus) {
                    leftImage.setSelected(true);
                    if (!TextUtils.isEmpty(editText.getText())) {
                        clearBtn.setVisibility(VISIBLE);
                        if (type == TYPE_PASSWORD) {
                            eyeBtn.setVisibility(VISIBLE);
                        }
                    }
                } else {
                    if (TextUtils.isEmpty(editText.getText())) {
                        leftImage.setSelected(false);
                    } else {
                        leftImage.setSelected(true);
                    }
                    clearBtn.setVisibility(GONE);
                    eyeBtn.setVisibility(GONE);
                }
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    clearBtn.setVisibility(GONE);
                    eyeBtn.setVisibility(GONE);
                } else {
                    clearBtn.setVisibility(VISIBLE);
                    if (type == TYPE_PASSWORD) {
                        eyeBtn.setVisibility(VISIBLE);
                    }
                }
                String content = editText.getText().toString();
                if(!TextUtils.isEmpty(content)) {
                    mInputCount = content.length();
                } else {
                    mInputCount = 0;
                }
            }
        });
        clearBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
                if (!editText.isFocused()) {
                    leftImage.setSelected(false);
                }
            }
        });
        eyeBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                eyeBtn.setSelected(!eyeBtn.isSelected());
                if (eyeBtn.isSelected()) {
                    editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        getAuthcodeTV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!getAuthcodeTV.isSelected()) {
                    sendVerifyCode();
                }
            }
        });
    }

    public int getInputCount() {
        return mInputCount;
    }

    public void addTextWatcher(MyTextWatcher myTextWatcher) {
        editText.addTextChangedListener(myTextWatcher);
    }

    public EditText getEditText() {
        return editText;
    }

    public String getText() {
        return editText.getText().toString().trim();
    }

    public void setType(int type) {
        this.type = type;
        removeAllViews();
        initView();
    }

    public String getAuthImage() {
        return authImage;
    }

    public void setPhone(String phone, String type) {
        this.authPhone = phone;
        this.authType = type;
    }

    private void sendVerifyCode() {
        if (TextUtils.isEmpty(authPhone) || !ValidityUtils.checkPhone(authPhone)) {
            MyToast.show("请输入正确的手机号");
            return;
        }
//        ProgressDialog progressDialog = new ProgressDialog(getContext());
//        progressDialog.show();
        requestAuthCode();
    }

    private final String TAG_REGISTER_CODE = "registerCode";
    private void requestAuthCode() {

        if (mUserApi == null) {
            mUserApi = new UserApi();
        }

        if(mIsRegister) {
            registerCode();
        } else {
            findPwdCode();
        }
    }

    private void showImageDialog(String url) {
        /*ImageAuthDialog imageAuthDialog = new ImageAuthDialog(getContext());
        imageAuthDialog.setUrl(url).show();
        imageAuthDialog.setOnConfirmListener(new ImageAuthDialog.OnConfirmListener() {
            @Override
            public void onConfirm(String text) {
                authImage = text;
                requestAuthCode(null);
            }
        });*/
    }

    private String captcha;

    /**
     * 注册验证码
     */
    private void registerCode() {
        Map<String, String> params = new HashMap<>();
        params.put("member_phone", authPhone);
        params.put("register_type", "mobile");

        if(!TextUtils.isEmpty(captcha)) {
            params.put("captcha", captcha);
        }

        mUserApi.registerCode(TAG_REGISTER_CODE, params, new SOARHttpCallback<SOARBaseModel<UserModel>>() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                SoarLoadDialog.showLoadDialog(getContext(), "验证码获取中...");
            }

            @Override
            public void onRequestSuccess(Object response) {
                // 发送成功的话开始倒计时
                MyToast.show("验证码发送中...");
                sendVerfyCodeSuccess();
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
                SoarLoadDialog.closeLoadDialog();
            }
        });
    }

    /**
     * 设置是否是注册的
     * @param isRegister
     */
    public void setGetCodeType(boolean isRegister) {
        mIsRegister = isRegister;
    }

    private final String TAG_FIND_PWD = "findPwd";

    /**
     * 忘记密码发送验证码
     */
    private void findPwdCode() {
        Map<String, String> params = new HashMap<>();
        params.put("member_phone", authPhone);
        params.put("find_passwrod_type", "mobile");
        mUserApi.resetPasswordCode(TAG_FIND_PWD, params, new SOARHttpCallback<SOARBaseModel<UserModel>>() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                SoarLoadDialog.showLoadDialog(getContext(), "验证码获取中...");
            }

            @Override
            public void onRequestSuccess(Object response) {
                // 发送成功的话开始倒计时s
                MyToast.show("验证码发送中...");
                sendVerfyCodeSuccess();
            }


            @Override
            public void onAfter(int id) {
                super.onAfter(id);
                SoarLoadDialog.closeLoadDialog();
            }
        });
    }

    private void sendVerfyCodeSuccess() {
        getAuthcodeTV.setSelected(true);
        myCountDownTimer = new MyCountDownTimer(AUTHCODE_INTERVAL, 1000);
        myCountDownTimer.start();
    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long currentNum = millisUntilFinished / 1000;
            getAuthcodeTV.setText(currentNum + " s");

            getAuthcodeTV.setUnSelected();
            getAuthcodeTV.setEnabled(false);
//            getAuthcodeTV.setTextColor(getResources().getColor(R.color.white));
        }

        @Override
        public void onFinish() {
            getAuthcodeTV.setEnabled(true);
            getAuthcodeTV.setSelected(false);
            getAuthcodeTV.setText("重新发送");
            getAuthcodeTV.setSelected();
//            getAuthcodeTV.setTextColor(getResources().getColor(R.color.color_bg));
        }
    }

    public void setGetCodeStatus(boolean flag) {
        if (getAuthcodeTV != null) {
            getAuthcodeTV.setSelected(!flag);
        }
        getAuthcodeTV.setTextColor(getResources().getColor(R.color.color_bg));
    }
}
